# 萤石 python获取直播地址和画面
# https://blog.csdn.net/qq_35498696/article/details/106857379

import cv2
import sys
import requests
import json
class YingShiLiveUrl:
    def __init__(self,appKey,appSecret,mode):
        self.appKey=appKey
        self.appSecret=appSecret
        self.accessToken="at.037okw941hvea8ey9yatd39n4iy6l4dd-9rjdsxx935-0sm8s66-o5syminur"
        self.mode=mode
    def get_accessToken(self):
        appKey=self.appKey
        appSecret=self.appSecret
        url = "https://open.ys7.com/api/lapp/token/get"
        data = {
            "POST" : "/api/lapp/token/get HTTP/1.1",
            "Host":"open.ys7.com",
            "Content-Type": "application/x-www-form-urlencoded",
            "appKey":appKey,
            "appSecret":appSecret
        }
        res = requests.post(url=url,data=data)
        resJson=json.loads(res.text)
        accessToken=resJson['data']['accessToken']
        self.accessToken=accessToken
    def get_VIDEO_URL(self):
        accessToken=self.accessToken
        url='https://open.ys7.com/api/lapp/live/video/list'
        data = {
            "POST" : "/api/lapp/token/get HTTP/1.1",
            "Host":"open.ys7.com",
            "Content-Type": "application/x-www-form-urlencoded",
            "accessToken":accessToken
        }
        res = requests.post(url=url,data=data)
        resJson=json.loads(res.text)
        urls=[]
        for i in range(len(resJson['data'])):
            url=resJson['data'][i][mode]
            urls.append(url)
        return urls
def get_camera(VIDEO_URL):
        cap = cv2.VideoCapture(VIDEO_URL)
        if (cap.isOpened() == False):
            print('!!! Unable to open URL')
            sys.exit(-1)
        fps = cap.get(cv2.CAP_PROP_FPS)
        wait_ms = int(1000/fps)
        print('FPS:', fps)
        while(True):
            # read one frame
            ret, frame = cap.read()
            cv2.imshow("fitcurve_.jpg",frame)
            if cv2.waitKey(wait_ms) & 0xFF == ord('q'):
                break
        cap.release()
        cv2.destroyAllWindows()
if __name__ == "__main__":
    appKey="26f2c5a6cb534167b2c22d28078839d8"
    appSecret="62f1e28b7b6783e3d477e8fcd0d4fc2d"
    mode='rtmp' # 'hdAddress'   #高清模式  # https://open.sq.ys7.com/doc/zh/book/index/address.html
    YingShi=YingShiLiveUrl(appKey,appSecret,mode)
    YingShi.get_accessToken()
    urls=YingShi.get_VIDEO_URL()
    print(urls)
    for url in urls:
    	get_camera(url)

# "liveAddress": "http://hls.open.ys7.com/openlive/ed98eeead4c843f898fef1c203313364.m3u8",
# "hdAddress": "http://hls.open.ys7.com/openlive/ed98eeead4c843f898fef1c203313364.hd.m3u8",
# "rtmp": "rtmp://rtmp.open.ys7.com/openlive/ed98eeead4c843f898fef1c203313364",
# "rtmpHd": "rtmp://rtmp.open.ys7.com/openlive/ed98eeead4c843f898fef1c203313364.hd",